import fs from 'node:fs';
import path from 'node:path';
import { Encoding } from '@p/utils';
import { getImageInfo } from './getImageInfo';
import { MdFileInfo } from '@p/main-windowObject';

/**
 * 读取markdown文件
 */
export function readMdFile(filePath: string, encoding: Encoding = 'utf-8'): Promise<MdFileInfo> {
	return new Promise((resolve, reject) => {
		// 文档信息对象
		const fileInfo: MdFileInfo = {
			filePath,
			fileName: path.basename(filePath),
			dirPath: path.dirname(filePath),
			size: 0,
			content: '',
			imageInfo: [],
			imageCount: {
				total: 0,
				url: 0,
				absolute: 0,
				relative: 0,
				base64URL: 0,
				unknown: 0,
			},
		};

		fs.stat(filePath, (err_1, stats) => {
			if (err_1) return reject(err_1);

			fileInfo.size = stats.size;

			fs.readFile(filePath, encoding, (err_2, data) => {
				if (err_2) return reject(err_2);

				if (data) {
					fileInfo.content = data;

					fileInfo.imageInfo = getImageInfo(fileInfo.content, fileInfo.dirPath);

					if (fileInfo.imageInfo.length > 0) {
						fileInfo.imageCount.total = fileInfo.imageInfo.length;

						fileInfo.imageInfo.forEach((item) => {
							switch (item.type) {
								case 'url':
									fileInfo.imageCount.url++;
									break;
								case 'absolute':
									fileInfo.imageCount.absolute++;
									break;
								case 'relative':
									fileInfo.imageCount.relative++;
									break;
								case 'base64URL':
									fileInfo.imageCount.base64URL++;
									break;
								case 'unknown':
								default:
									fileInfo.imageCount.unknown++;
									break;
							}
						});
					}
				}

				resolve(fileInfo);
			});
		});
	});
}
